#! /usr/bin/python
# -*- coding: utf-8 -*-
#
# $AIST_Release: 0.9.0 $
# Copyright 2011 Information Technology Research Institute, National
# Institute of Advanced Industrial Science and Technology
# 
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# 
#    http://www.apache.org/licenses/LICENSE-2.0
# 
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import sys

minTupleSize = 2
maxTupleSize = 22

def mkVars(fmt, sep, maxValue):
    return sep.join([fmt % x for x in xrange(0, maxValue)])

if len(sys.argv) < 1:
    sys.stderr.write("%s: no output file path\n" % sys.argv[0])
    sys.exit(1)

fp = open(sys.argv[1], "w")

fp.write("package parser\n\n")

fp.write("import scala.PartialFunction\n\n")
fp.write("import parser.Results._\n\n")

fp.write("object Tuple {\n")
fp.write("  def tupleMap(f: Any => Result[Any]): PartialFunction[Any, Result[Any]] = {\n")
fp.write("    val g: PartialFunction[Any, Result[Any]] = {\n")
for i in xrange(minTupleSize, maxTupleSize + 1):
    commaSepXs = mkVars("x%d", ", ", i)
    fp.write("      case (%s) =>" % commaSepXs)
    fp.write("(%s).map {" % mkVars("f(x%d)", " ~ ", i))
    fp.write("case (%s) => (%s) }\n" % (mkVars("x%d", " ~ ", i), commaSepXs))

fp.write("    }\n")
fp.write("    return g\n")
fp.write("  }\n")


fp.write("  def tupleForeach(f: Any => Result[Unit]): PartialFunction[Any, Result[Unit]] = {\n")
fp.write("    val g: PartialFunction[Any, Result[Unit]] = {\n")
for i in xrange(minTupleSize, maxTupleSize + 1):
    fp.write("      case (%s) =>" % mkVars("x%d", ", ", i))
    fp.write("(%s).map { _ => Unit}\n" % mkVars("f(x%d)", " ~ ", i))

fp.write("    }\n")
fp.write("    return g\n")
fp.write("  }\n")

fp.write("}\n")

fp.close()
